/*
 * @Author       : wfl
 * @LastEditors  : wfl
 * @description  :
 * @updateInfo   :
 * @Date         : 2023-12-08 17:45:44
 * @LastEditTime : 2023-12-08 18:10:40
 */
import { MapScreenMapEntity } from './../entity/map';
import { Config, Provide } from '@midwayjs/decorator';
import { BaseService, CoolFileConfig, MODETYPE } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository, In } from 'typeorm';
const fs = require('fs');
const path = require('path');

/**
 * 文件信息
 */
@Provide()
export class MapScreenService extends BaseService {
  @InjectEntityModel(MapScreenMapEntity)
  mapScreenEntity: Repository<MapScreenMapEntity>;

  @Config('cool.file')
  config: CoolFileConfig;

  async deleteById(id) {
    const fileds = await this.mapScreenEntity.find({
      where: {
        id: In([id]),
      },
    });

    if (fileds) {
      const fileDir = fileds?.[0].file;
      if (!fileDir) return await this.mapScreenEntity.delete([id]);
      const dir = fileDir.substring(0, fileDir.lastIndexOf('/'));

      const directoryPath = path.join(this.baseApp.getBaseDir(), '..', dir);
      const fileNamesArray = fileds.map(v => `${v.uid}`);
      fs.readdir(directoryPath, (err, files) => {
        if (err) {
          console.error('Error reading directory:', err);
          return;
        }

        files.forEach(file => {
          if (fileNamesArray.includes(file)) {
            const filePath = `${directoryPath}/${file}`;
            fs.unlink(filePath, err => {
              if (err) {
                console.error('Error deleting file:', err);
              } else {
                console.log('File deleted:', filePath);
              }
            });
          }
        });
      });
    }

    return await this.mapScreenEntity.delete([id]);
  }
}
